package com.olive.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.olive.dto.JwtUserDto;
import com.olive.entity.Authority;
import com.olive.entity.Role;
import com.olive.entity.User;
import com.olive.mapper.AuthorityMapper;
import com.olive.service.RoleService;
import com.olive.service.UserService;

import cn.hutool.core.util.StrUtil;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthorityMapper authorityMapper;

    @Override
    public JwtUserDto loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名获取用户
        User user = userService.getUserByName(username);
        if (user == null ){
            throw new BadCredentialsException("用户名或密码错误");
        }
        List<Role> roles = roleService.loadRolesByUsername(username);
        Set<String> roleInfos = roles.stream().map(Role::getRoleName).collect(Collectors.toSet());
        List<Authority> authorities = authorityMapper.loadPermissionByRoleCode(roleInfos);
        List<String> authorityNames = authorities.stream().map(Authority::getAuthorityName).filter(StrUtil::isNotEmpty).collect(Collectors.toList());
        authorityNames.addAll(roleInfos.stream().map(roleName->"ROLE_"+roleName).collect(Collectors.toList()));
        return new JwtUserDto(user, new HashSet<>(roles), authorityNames);
    }
}

